using Making.Avalonia.WebView.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Runtime.InteropServices;

namespace Making.Avalonia.WebView.Core.Services;

public static class WebViewProviderFactory
{
    private static readonly Dictionary<SupportedPlatform, Type> ProviderTypes = new();
    
    public static void RegisterProvider<T>(SupportedPlatform platform) where T : class, IWebViewProvider
    {
        ProviderTypes[platform] = typeof(T);
    }
    
    public static IWebViewProvider CreateProvider(IServiceProvider? serviceProvider = null)
    {
        var platformType = GetCurrentPlatform();
        
        if (!ProviderTypes.TryGetValue(platformType, out var providerType))
        {
            throw new PlatformNotSupportedException($"WebView is not supported on {platformType}");
        }
        
        if (serviceProvider != null)
        {
            return (IWebViewProvider)ActivatorUtilities.CreateInstance(serviceProvider, providerType);
        }
        
        return (IWebViewProvider)Activator.CreateInstance(providerType)!;
    }
    
    private static SupportedPlatform GetCurrentPlatform()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            return SupportedPlatform.Windows;
        
        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            return SupportedPlatform.MacOS;
            
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            return SupportedPlatform.Linux;
            
        throw new PlatformNotSupportedException("Unsupported platform");
    }
}

public enum SupportedPlatform
{
    Windows,
    MacOS,
    Linux
}